<?php

class Officer_model extends CI_Model {

    function OfficerModel() {
        parent::Model();
    }

    function getOfficer($condition = "") {
        $q = "SELECT Officer.ID , Officer.name  FROM Officer ";
        if ($condition != "") {
            $q .= " WHERE name LIKE '%$condition%'";
        }
        $query = $this->db->query($q."  LIMIT 300");
        return $query->result_array();
    }

    function officerDatatable() {

        $aColumns = array('Officer.ID', 'Officer.name', 'Officer_Function.name');
        $where = '';

        if (isset($_GET['iSortCol_0'])) {
            for ($i = 0; $i < intval(check_get('iSortingCols')); $i++) {
                if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
                    $this->db->order_by($aColumns[intval($_GET['iSortCol_' . $i])], $_GET['sSortDir_' . $i]);
                }
            }
        } else {
            $this->db->order_by("Officer.name", "ASC");
        }
        $order = $this->db->ar_orderby;

        if ($_GET['sofficial_name'] != '') {
            $where .= $where != "" ? " AND " : " ";
            $where .= " Officer.ID = " . check_get('sofficial_name');
        }

        if ($_GET['sofficial_function'] != '') {
            $where .= $where != "" ? " AND " : " ";
            $where .= " Officer_Function.ID = " . check_get('sofficial_function');
        }

        if ($where != '')
            $this->db->where($where);

        $this->db->select('Officer.ID');
        $this->db->join('Officer_Function', 'Officer_Function.ID= Officer.function_ID', 'inner');
        $totalQuery = $this->db->get('Officer');

        if ($where != '')
            $this->db->where($where);

        $this->db->select('Officer.ID, Officer.name officerName, Officer_Function.name functionName');
        $this->db->join('Officer_Function', 'Officer_Function.ID= Officer.function_ID', 'inner');
        $query = $this->db->get('Officer', check_get('iDisplayStart'), check_get('iDisplayLength'), $order);
        $officers = $query->result_array();
        $aaData = array();
        $i = 0;
        foreach ($officers as $officer) {
            $data = array(++$i, $officer['functionName'], $officer['officerName'], "<a class='edit-btn edit-officer' title='កែប្រែ' rel='{$officer['ID']}'>&nbsp;</a>", "<a class='delete-btn delete-officer' rel='{$officer['ID']}' title='លុប'>&nbsp;</a>");
            array_push($aaData, $data);
        }


        $output = array(
            "sEcho" => intval(!empty($_GET['sEcho']) ? $_GET['sEcho'] : ""),
            "iTotalRecords" => $query->num_rows(),
            "iTotalDisplayRecords" => $totalQuery->num_rows(),
            "aaData" => $aaData
        );
        return $output;
    }

    function read() {
        $query = $this->db->get_where('Officer', array('ID' => check_post('id')));
        return $query->result_array();
    }

}

?>
